﻿using System;
using UnityEngine;
using Yoozoo.Gta.Common;

namespace WorldMap
{
    public class UnionTrialBossViewCheck : MonoBehaviour
    {
        public long unionId;
        public int maxHp;
        public int currentHp;
        public long uid;
        public int type;
        
        [Header("视野检测时间间隔")]
        public float checkTime = 0.5f;
        private float _curCheckTime;
        
        private Camera _camera;

        public bool visible = false;
        
        private void Awake()
        {
            _camera = WorldCameraManager.mainCamera;
        }

        private void OnEnable()
        {
            
        }

        private void OnDisable()
        {
            //if (visible)
            {
                visible = false;
                TriggerViewStatus();
            }
        }

        public void UpdateMaxHp(int maxHp)
        {
            if (maxHp != this.maxHp && maxHp != 0)
            {
                this.maxHp = maxHp;
                TriggerViewStatus();
            }
        }
        private void Update()
        {
            _curCheckTime += Time.deltaTime;
            if (_curCheckTime > checkTime)
            {
                bool vis = true;
                Vector3 pos = transform.position;
                Vector3 viewPos = _camera.WorldToViewportPoint(pos);

                if (viewPos.z < 0)
                {
                    vis = false;
                }

                if (viewPos.z > _camera.farClipPlane)
                {
                    vis = false;
                }

                if (viewPos.x < 0 || viewPos.y < 0 || viewPos.x > 1 || viewPos.y > 1)
                {
                    vis = false;
                }
                
                //if (visible != vis)
                {
                    visible = vis;
                    TriggerViewStatus();
                }
                
                _curCheckTime = 0;
            }
        }

        private void TriggerViewStatus()
        {
            ResidentHandler.Inst.GetFunction("CityLuaFunction.onUnionTrialBossViewStatus").Action(
                unionId,maxHp,uid,type,visible);
        }
    }
}